package com.hx.skyDrive.controller;

import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hx.skyDrive.biz.UsersBiz;
import com.hx.skyDrive.entity.Users;
import com.hx.skyDrive.util.SendMailUtil;
import com.hx.skyDrive.util.StringUtil;

@RestController
@RequestMapping("user")
public class UserController {
	@Autowired
	private UsersBiz usersBiz;
	
	@Autowired
	private SendMailUtil sendMail;
	
	@RequestMapping("login")
	public Users login(String email,String pwd,String UA,HttpSession session){
		if( StringUtil.checkNull(email,pwd) ){
			return new Users(-1, "未登录", "未登录");
		}
		Users user = null;
		if(UA == null || !"admin".equals(UA)){
			user = usersBiz.login(new Users(email,pwd));
		}else if("admin".equals(UA)){
			user = usersBiz.adminLogin(new Users(email,pwd));
		}
		
		if( user != null ){
			session.setAttribute("currentLoginUser", user);
			return user;
		}
		return new Users(-1, "未登录", "未登录");
	}
	
	@RequestMapping("/checkLogin")
	public Users checkLogin(HttpSession session){
		Object obj = session.getAttribute("currentLoginUser");
		if(obj == null){
			return new Users(-1, "未登录", "未登录");
		}else{
			return (Users) obj;
		}
	}
	
	@RequestMapping("/code")
	public int sendCode(String email,HttpSession session){
		if(StringUtil.checkNull(email)){
			return -2;	//邮箱为空
		}
		int code = (int)((Math.random()*9+1)*100000);
		String mainText = "<!DOCTYPE><html><h1>您的验证码为: <font color='red'><b>"+code+"</b></font></h1> <h1>请您在3分钟内使用</h1></html>";
		
		boolean result = sendMail.sendEmail(email, "尊敬的用户", mainText, "HUATHY SKY DRIVE");
		if(result){
			session.setAttribute("regCode", code);	//code存session
			
			Timer timer = new Timer();	//创建定时器
			timer.schedule(new TimerTask() {	//创建定时任务
				@Override
				public void run() {
					session.removeAttribute("regCode");
				}
			}, 180000);		//3分钟后执行1次
			
			return 1;
		}
		return -1;
	}
	
	@RequestMapping("reg")
	public int reg(String email,String pwd,String code,HttpSession session){
		if(StringUtil.checkNull(email,pwd,code)){
			return -2;	//信息不完整
		}
		Object codeObj = session.getAttribute("regCode");
		if(codeObj == null){
			return -3;		//验证码过期
		}
		String regCode = String.valueOf(codeObj);
		if(!code.equals(regCode)){
			return -4;	//验证码错误
		}
		int result = usersBiz.reg(new Users(email,pwd));
		return result;
	}
}
